<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="企业名称" prop="enterpriseName">
              <el-input v-model="queryParams.enterpriseName" placeholder="请输入企业名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="queryParams.contactPerson" placeholder="请输入联系人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="queryParams.phone" placeholder="请输入联系电话" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="片区" prop="districtId">
              <el-select v-model="queryParams.districtId" placeholder="请选择片区" clearable style="width: 120px" @change="loadBuildingList">
                <el-option v-for="district in districtList" :key="district.id" :label="district.districtName" :value="district.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="楼宇" prop="housingId">
              <el-select v-model="queryParams.housingId" placeholder="请选择楼宇" clearable style="width: 120px">
                <el-option v-for="district in buildingList" :key="district.id" :label="district.housingName" :value="district.id" />
              </el-select>
            </el-form-item>

            <!-- <el-form-item label="楼层范围" prop="floorRange">
              <el-input-number v-model="queryParams.minFloor" placeholder="最小楼层" :min="1" :controls="false" style="width: 120px" />
              <span class="mx-2">-</span>
              <el-input-number v-model="queryParams.maxFloor" placeholder="最大楼层" :min="1" :controls="false" style="width: 120px" />
            </el-form-item> -->
            <el-form-item label="租期状态" prop="leaseStatus">
              <el-select v-model="queryParams.leaseStatus" placeholder="请选择租期状态" clearable style="width: 120px">
                <el-option label="全部" value="" />
                <el-option label="即将到期" value="2" />
                <el-option label="已到期" value="3" />
                <el-option label="已退租" value="4" />
              </el-select>
            </el-form-item>
            <!-- 新增租赁信息查询条件 -->

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>

              <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <!-- <template #header>
        <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template> -->

      <el-table border :data="tenantList" @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="id" align="center" prop="id" />
        <!-- <el-table-column label="合同编号" align="center" prop="intro" min-width="200" show-overflow-tooltip /> -->
        <el-table-column label="企业名称" align="center" prop="enterpriseName" width="260" show-overflow-tooltip />
        <el-table-column label="租赁面积" align="center" prop="leaseArea" width="100" />

        <el-table-column label="租赁开始时间" align="center" prop="leaseStart" min-width="200" show-overflow-tooltip :formatter="formatDate" />
        <el-table-column label="租赁结束时间" align="center" prop="leaseEnd" min-width="200" show-overflow-tooltip :formatter="formatDate" />
        <el-table-column label="剩余天数" align="center" prop="daysUntilExpiry" width="100">
          <template #default="scope">
            <span :class="{ 'text-red-500': scope.row.remainingDays < 60 }">
              {{ scope.row.remainingDays }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间 " align="center" prop="updateTime" width="120" />
        <!-- <el-table-column label="备注" align="center" prop="contactPhone" width="120" /> -->

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" fixed="right">
          <template #default="scope">
            <el-button link type="primary" v-if="scope.row.leaseStatus != 4" @click="handleUpdate(scope.row)">修改</el-button>

            <el-button link type="primary" v-if="scope.row.leaseStatus != 4 && roleSetting === 'admin'" @click="handleDelete(scope.row)"
              >删除</el-button
            >

            <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>

            <el-button link type="primary" v-if="scope.row.leaseStatus != 4" @click="handleOut(scope.row)">退租 </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改租户对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" append-to-body>
      <el-form ref="tenantFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="企业名称" prop="tenantCode">
              <el-select v-model="form.tenantCode" filterable placeholder="请搜索企业" style="width: 100%" clearable>
                <el-option v-for="item in QyList" :key="item.id" :label="item.enterpriseName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="租赁开始" prop="leaseStart">
              <el-date-picker v-model="form.leaseStart" type="date" placeholder="选择开始时间" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租赁结束" prop="leaseEnd">
              <el-date-picker v-model="form.leaseEnd" type="date" placeholder="选择结束时间" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="面积" prop="leaseArea">
              <el-input v-model="form.leaseArea" disabled placeholder="" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="租赁区域" prop="parkContractDetails">
              <el-table :data="form.parkContractDetails" border style="width: 100%; max-height: 200px; overflow-y: auto">
                <!-- <el-table-column prop="region" label="分区" width="120"></el-table-column> -->
                <el-table-column prop="housingName" label="楼宇" width="220"></el-table-column>
                <!-- <el-table-column prop="floor" label="楼层" width="120"></el-table-column> -->
                <el-table-column prop="houseName" label="房间" width="220"></el-table-column>
                <el-table-column prop="area" label="面积(㎡)" width="100"></el-table-column>
                <!-- <el-table-column prop="remark" label="备注" width="150"></el-table-column> -->
                <el-table-column label="操作" fixed="right">
                  <template #default="scope">
                    <el-button type="danger" size="small" @click="removeSelectedItem(scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-button type="primary" @click="showAddItemDialog" style="margin-top: 10px">选择房源</el-button>
            </el-form-item>
          </el-col>

          <!-- 楼层选择 -->

          <!-- 新增租赁信息字段 -->

          <!-- 新增图片上传 -->

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 合同详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="合同详情" width="800px" append-to-body>
      <el-card>
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 企业信息面板 -->
          <el-tab-pane label="企业信息">
            <el-row :gutter="20" class="mt-4">
              <el-col :span="6">
                <div class="text-center">
                  <el-avatar
                    :size="100"
                    :src="detailData.parkTenant.logoUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f42140.png'"
                    class="mb-2"
                  ></el-avatar>
                </div>
              </el-col>
              <el-col :span="18">
                <el-descriptions title="企业信息" :column="1" border>
                  <!-- <div class="font-bold text-xl" style="font-size: 13px">{{ detailData.parkTenant.enterpriseName }}</div> -->
                  <el-descriptions-item label="名称">{{ detailData.parkTenant.enterpriseName }}</el-descriptions-item>
                  <el-descriptions-item label="联系人">{{ detailData.parkTenant.contactPerson }}</el-descriptions-item>
                  <el-descriptions-item label="联系电话">{{ detailData.parkTenant.phone }}</el-descriptions-item>
                  <el-descriptions-item label="备注">{{ detailData.parkTenant.remark || '-' }}</el-descriptions-item>
                </el-descriptions>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 合同信息面板 -->
          <el-tab-pane label="合同信息">
            <el-descriptions title="租赁信息" :column="2" border>
              <el-descriptions-item label="租赁开始时间">{{ formatDate2(detailData.leaseStart) }}</el-descriptions-item>
              <el-descriptions-item label="租赁结束时间">{{ formatDate2(detailData.leaseEnd) }}</el-descriptions-item>
              <el-descriptions-item label="租赁面积">{{ detailData.leaseArea }} ㎡</el-descriptions-item>
              <el-descriptions-item label="租赁区域">
                <div
                  v-for="item in detailData.parkContractDetails"
                  :key="item.id"
                  class="mb-1"
                  style="width: 100%; max-height: 200px; overflow-y: auto"
                >
                  {{ item.housingName }} - {{ item.houseName }} {{ item.houseArea }}
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="备注" :span="2">{{ detailData.remark || '-' }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>

          <!-- 退租信息面板 -->
          <el-tab-pane label="退租信息">
            <el-descriptions title="退租详情" :column="2" border v-if="detailData.parkContractCheckOut">
              <el-descriptions-item label="退租日期">{{ formatDate2(detailData.parkContractCheckOut.checkOutTime) }}</el-descriptions-item>
              <el-descriptions-item label="是否欠租">{{ detailData.parkContractCheckOut.isOwed ? '是' : '否' }}</el-descriptions-item>
              <el-descriptions-item label="退租原因" :span="2">{{ detailData.parkContractCheckOut.cause || '-' }}</el-descriptions-item>
              <el-descriptions-item label="退租备注" :span="2">{{ detailData.parkContractCheckOut.remark || '-' }}</el-descriptions-item>
            </el-descriptions>
            <div v-else class="text-center text-gray-500 py-10">暂无退租信息</div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增项目弹窗 -->
    <el-dialog v-model="addItemDialog.visible" :title="addItemDialog.title" width="500px" append-to-body>
      <el-form :model="newItemData" label-width="80px">
        <el-form-item label="片区">
          <el-select v-model="newItemData.region" placeholder="请选择片区" clearable style="width: 100%" @change="handleAreaChange">
            <el-option v-for="district in districtList" :key="district.id" :label="district.districtName" :value="district.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="楼宇">
          <el-select v-model="newItemData.building" placeholder="请选择楼宇" @change="handleHouseChange">
            <el-option v-for="building in buildingSelList" :key="building.id" :label="building.housingName" :value="building.id" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="楼层">
          <el-select v-model="newItemData.floor" placeholder="请选择楼层" @change="handleAddItemFloorChange">
            <el-option v-for="floor in floorList" :key="floor.id" :label="floor.name" :value="floor.name" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="房间">
          <el-select v-model="newItemData.buildingDetail" placeholder="请选择房间">
            <el-option v-for="building in buildingDetailSelList" :key="building.id" :label="building.houseName" :value="building.id" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="面积">
          <el-input-number v-model="newItemData.area" placeholder="请输入面积" :min="0" :precision="2" controls-position="right" style="width: 100%">
            <template #append>㎡</template>
          </el-input-number>
        </el-form-item> -->
        <el-form-item label="备注">
          <el-input v-model="newItemData.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addItemSubmit">确 定</el-button>
          <el-button @click="addItemDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 退租确认对话框 -->
    <el-dialog v-model="dialogVisibleOut" title="租户退租" width="500px">
      <el-form ref="outForm" :model="formDataOut" :rules="rulesOut" label-width="120px">
        <el-form-item label="退租日期" prop="checkOutTime">
          <el-date-picker v-model="formDataOut.checkOutTime" type="date" placeholder="选择退租日期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="退租原因" prop="cause">
          <el-input v-model="formDataOut.cause" type="textarea" rows="3" placeholder="请输入退租原因" />
        </el-form-item>
        <el-form-item label="是否欠租" prop="isOwed">
          <el-switch v-model="formDataOut.isOwed" :active-value="1" :inactive-value="0" />
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="formDataOut.remark" type="textarea" rows="2" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisibleOut = false">取消</el-button>
        <el-button type="primary" @click="submitOutForm">确认提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="Tenant">
import {
  listContract,
  getBuildingList,
  listHousingDetails,
  listTenant,
  removeContract,
  addContract,
  updateContract,
  checkOutContract,
  listDistrict,
  getContantId,
  downloadImage
} from '@/api/system/building';

import { selectTenantPackage } from '@/api/system/tenantPackage';
import { TenantVO, TenantForm, TenantQuery, SelectedItem } from '@/api/system/tenant/types';
import { TenantPkgVO } from '@/api/system/tenantPackage/types';
import { ref, reactive, toRefs } from 'vue';
import { ComponentInternalInstance, getCurrentInstance } from 'vue';
import { ElForm, ElMessage } from 'element-plus';
import { useUserStore } from '@/store/modules/user';

interface Building {
  id: number;
  name: string;
}

interface Floor {
  id: number;
  name: string;
  buildingId: number;
}

interface Room {
  id: number;
  name: string;
  floorId: number;
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_tenant_status } = toRefs(proxy?.useDict('sys_tenant_status'));

const userStore = useUserStore();
const userId = ref(userStore.userId);
const tenantList = ref<any>([]);
const packageList = ref<TenantPkgVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<InstanceType<typeof ElForm>>();
const tenantFormRef = ref<InstanceType<typeof ElForm>>();

// 楼宇楼层房间相关数据
const buildingList = ref<Building[]>([]);
const floorList = ref<Floor[]>([]);
const roomList = ref<Room[]>([]);

// 片区列表
const districtList = ref<any[]>([]);

const dialog = reactive({
  visible: false,
  title: ''
});

// 新增项目弹窗相关
const addItemDialog = reactive({
  visible: false,
  title: '新增房间'
});

const initNewItemData = {
  region: '',
  building: '',
  buildingDetail: '',
  remark: ''
};

// 详情弹窗相关变量
const detailDialogVisible = ref(false);
const activeTab = ref('0');
const detailData = ref<any>({ parkContractDetails: [], checkOutInfo: null });

interface NewItemData {
  region: string;
  building: string;
  floor: string;
  room: string;
  area: number;
  remark: string;
  buildingDetail?: string | number;
}
const newItemData = ref({ region: '', building: '', floor: '', room: '', area: 0, remark: '' });

const initFormData: TenantForm = {
  id: undefined,
  tenantId: undefined,
  contactUserName: '',
  contactPhone: '',
  username: '',
  password: '',
  companyName: '',
  licenseNumber: '',
  domain: '',
  address: '',
  intro: '',
  remark: '',
  packageId: '',
  expireTime: '',
  accountCount: 0,
  status: '0',
  region: '',
  building: '',
  floor: '',
  roomNumber: '',
  // 新增字段
  logoUrl: '',
  licenseImageUrl: '',
  leaseArea: 0,
  leaseStartTime: '',
  leaseEndTime: '',
  buildingId: undefined,
  floorId: undefined,
  roomId: undefined,
  buildingIds: [],
  floorIds: [],
  roomIds: [],
  selectedItems: []
};

interface FormData {
  id: string;
  enterpriseName: string;
  leaseStart: string;
  leaseEnd: string;
  contactPerson: string;
  parkContractDetails: any[];
  logoUrl?: string;
  licenseImageUrl?: string;
  floorIds?: number[];
  roomIds?: number[];
  buildingIds?: number[];
}

const form = ref<any>({ id: '', enterpriseName: '', leaseStart: '', leaseEnd: '', contactPerson: '', parkContractDetails: [] });
const roleSetting = ref(localStorage.getItem('username'));
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tenantId: '',
    companyName: '',
    contactUserName: '',
    contactPhone: '',
    region: '',
    building: '',
    expiryRange: '',
    minLeaseArea: undefined,
    maxLeaseArea: undefined,
    leaseStartTime: '',
    leaseEndTime: ''
  },
  rules: {
    enterpriseName: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
    leaseStart: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
    leaseEnd: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
    parkContractDetails: [{ required: true, message: '请选择租赁位置', trigger: 'blur' }]
  }
});

const { queryParams, rules } = toRefs(data);

// 企业名称下拉框相关数据
const companyOptions = ref([]);
const companySelectLoading = ref(false);

// 模拟的企业名称数据
const companies = [
  { value: '1', label: '企业1' },
  { value: '2', label: '企业2' },
  { value: '3', label: '企业3' },
  { value: '4', label: '企业4' },
  { value: '5', label: '企业5' }
];

// 文件上传相关
const uploadUrl = '/api/common/upload';
const uploadHeaders = {
  Authorization: 'Bearer ' + userStore.token
};

const handleLogoSuccess = (response: any) => {
  form.value.logoUrl = response.url;
};

const beforeLogoUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isImage) {
    proxy?.$modal.msgError('只能上传图片文件!');
  }
  if (!isLt2M) {
    proxy?.$modal.msgError('图片大小不能超过 2MB!');
  }
  return isImage && isLt2M;
};

const handleLicenseSuccess = (response: any) => {
  form.value.licenseImageUrl = response.url;
};

const beforeLicenseUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isImage) {
    proxy?.$modal.msgError('只能上传图片文件!');
  }
  if (!isLt2M) {
    proxy?.$modal.msgError('图片大小不能超过 2MB!');
  }
  return isImage && isLt2M;
};

// 计算表格中的租期时长
const calculateTableLeaseDuration = (row: TenantVO) => {
  if (!row.leaseStartTime || !row.leaseEndTime) return '-';

  const start = new Date(row.leaseStartTime);
  const end = new Date(row.leaseEndTime);

  if (isNaN(start.getTime()) || isNaN(end.getTime())) return '-';

  const diffTime = end.getTime() - start.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  if (diffDays < 30) {
    return `${diffDays}天`;
  } else if (diffDays < 365) {
    const months = Math.round(diffDays / 30);
    return `${months}个月`;
  } else {
    const years = Math.round(diffDays / 365);
    return `${years}年`;
  }
};

// 远程搜索方法
const remoteMethod = (query: string) => {
  if (query !== '') {
    companySelectLoading.value = true;
    setTimeout(() => {
      companySelectLoading.value = false;
      companyOptions.value = companies.filter((item) => {
        return item.label.toLowerCase().includes(query.toLowerCase());
      });
    }, 200);
  } else {
    companyOptions.value = [];
  }
};

// 获取租户套餐列表
const getTenantPackage = async () => {
  const res = await selectTenantPackage();
  packageList.value = res.data;
};

// 获取位置信息文本
const getLocationText = (row: TenantVO) => {
  const parts = [];
  if (row.region) parts.push(row.region);
  if (row.building) parts.push(row.building);
  if (row.floor) parts.push(row.floor);
  if (row.roomNumber) parts.push(row.roomNumber);
  return parts.join(' - ') || '-';
};

// 加载楼宇列表
const loadBuildingList = async () => {
  queryParams.value.housingId = '';
  buildingList.value = [];
  try {
    const res = await getBuildingList({ pageNum: 1, pageSize: 100, districtId: queryParams.value.districtId });
    buildingList.value = res.rows;
  } catch (error) {
    // console.error('获取片区列表失败:', error);
  }
};

// 加载片区列表
const getDistrictList = async () => {
  try {
    const res = await listDistrict({ pageNum: 1, pageSize: 100 });
    districtList.value = res.rows;
  } catch (error) {
    console.error('获取片区列表失败:', error);
  }
};

// 查看详情方法
const handleDetail = async (row: any) => {
  const res = await getContantId(row.id);
  const contractDetails = res.data;

  detailData.value = { ...contractDetails };
  detailData.value.parkTenant.logoUrl = await getPhotoUrl(detailData.value.parkTenant.logoId);
  console.log('======detailData.value', detailData.value);
  detailDialogVisible.value = true;
};

const getPhotoUrl = async (id: any) => {
  if (id) {
    try {
      // 发送POST请求获取图片流
      const response = await downloadImage(id);
      console.log('response', response);
      // 验证响应是否为blob格式
      if (response instanceof Blob) {
        // 将blob转换为Data URL
        return URL.createObjectURL(response);
      } else {
        console.error('响应不是blob格式:', response);
      }
    } catch (error) {
      console.error('获取图片失败:', error);
    }
  }
};

// 加载楼层列表
const loadFloorList = (buildingId: number) => {
  floorList.value = [
    { id: 1, name: '1楼', buildingId: 1 },
    { id: 2, name: '2楼', buildingId: 1 },
    { id: 3, name: '3楼', buildingId: 1 },
    { id: 4, name: '1楼', buildingId: 2 },
    { id: 5, name: '2楼', buildingId: 2 },
    { id: 6, name: '1楼', buildingId: 3 }
  ].filter((floor) => floor.buildingId === buildingId);
};

// 加载房间列表
const loadRoomList = (floorId: number) => {
  roomList.value = [
    { id: 1, name: '101', floorId: 1 },
    { id: 2, name: '102', floorId: 1 },
    { id: 3, name: '201', floorId: 2 },
    { id: 4, name: '202', floorId: 2 },
    { id: 5, name: '301', floorId: 3 },
    { id: 6, name: '401', floorId: 4 }
  ].filter((room) => room.floorId === floorId);
};

// 楼宇变化处理
const handleBuildingChange = (buildingIds: Array<string | number>) => {
  form.value.floorIds = [];
  form.value.roomIds = [];

  // 如果没有选择楼宇，则清空楼层列表
  if (!buildingIds || buildingIds.length === 0) {
    floorList.value = [];
    roomList.value = [];
    return;
  }

  // 收集所有选中楼宇的楼层
  const allFloors: Floor[] = [];
  buildingIds.forEach((buildingId) => {
    const floors = [
      { id: 1, name: '1楼', buildingId: 1 },
      { id: 2, name: '2楼', buildingId: 1 },
      { id: 3, name: '3楼', buildingId: 1 },
      { id: 4, name: '1楼', buildingId: 2 },
      { id: 5, name: '2楼', buildingId: 2 },
      { id: 6, name: '1楼', buildingId: 3 }
    ].filter((floor) => floor.buildingId === Number(buildingId));
    allFloors.push(...floors);
  });

  floorList.value = allFloors;
};

// 楼层变化处理
const handleFloorChange = (floorIds: Array<string | number>) => {
  form.value.roomIds = [];

  // 如果没有选择楼层，则清空房间列表
  if (!floorIds || floorIds.length === 0) {
    roomList.value = [];
    return;
  }

  // 收集所有选中楼层的房间
  const allRooms: Room[] = [];
  floorIds.forEach((floorId) => {
    const rooms = [
      { id: 1, name: '101', floorId: 1 },
      { id: 2, name: '102', floorId: 1 },
      { id: 3, name: '201', floorId: 2 },
      { id: 4, name: '202', floorId: 2 },
      { id: 5, name: '301', floorId: 3 },
      { id: 6, name: '401', floorId: 4 }
    ].filter((room) => room.floorId === Number(floorId));
    allRooms.push(...rooms);
  });

  roomList.value = allRooms;
};

const QyList = ref([]);
const getQyList = async () => {
  const res = await listTenant({ pageNum: 1, pageSize: 200 });
  QyList.value = res.rows;
};

/** 查询租户列表 */
const getList = async () => {
  loading.value = true;
  const res = await listContract(queryParams.value);
  tenantList.value = res.rows.map((tenant: TenantVO) => {
    calculateExpiryStatus(tenant);
    return tenant;
  });
  total.value = res.total;
  loading.value = false;
};

// 计算租户到期状态
const calculateExpiryStatus = (tenant: TenantVO) => {
  if (!tenant.expireTime) {
    tenant.daysUntilExpiry = 0;
    tenant.expiryStatus = 'normal';
    return;
  }

  const expireDate = new Date(tenant.expireTime);
  const currentDate = new Date();
  const diffTime = expireDate.getTime() - currentDate.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  tenant.daysUntilExpiry = diffDays;

  if (diffDays < 0) {
    tenant.expiryStatus = 'expired';
  } else if (diffDays <= 30) {
    tenant.expiryStatus = 'expiring_soon';
  } else {
    tenant.expiryStatus = 'normal';
  }
};

// 获取到期标签类型
const getExpiryTagType = (row: any) => {
  switch (row.expiryStatus) {
    case 'expired':
      return 'danger';
    case 'expiring_soon':
      return 'warning';
    default:
      return 'success';
  }
};

// 租户状态修改
const handleStatusChange = async (row: TenantVO) => {
  // const text = row.status === '0' ? '启用' : '停用';
  // try {
  //   await proxy?.$modal.confirm(`确认要"${text}""${row.companyName}"租户吗？`);
  //   await changeTenantStatus(row.id, row.tenantId, row.status);
  //   proxy?.$modal.msgSuccess(text + '成功');
  // } catch {
  //   row.status = row.status === '0' ? '1' : '0';
  // }
};

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
};

// 表单重置
const reset = () => {
  // form.value = { ...initFormData };
  tenantFormRef.value?.resetFields();
  form.value.parkContractDetails = [];
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
  /* loadDistrictList(); */
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection: TenantVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  form.value = { id: '', enterpriseName: '', leaseStart: '', leaseEnd: '', contactPerson: '', parkContractDetails: [] };
  // getTenantPackage();
  // loadBuildingList();
  // loadDistrictList();
  dialog.visible = true;
  dialog.title = '添加';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: any) => {
  reset();

  const res = await getContantId(row.id);
  // const contractDetails = res.data;
  form.value = res.data;
  form.value.tenantCode = Number(form.value.tenantCode);
  dialog.visible = true;
  dialog.title = '修改';
};

// 移除楼宇
const removeBuilding = (buildingId: string | number) => {
  form.value.buildingIds = form.value.buildingIds.filter((id) => id !== buildingId);
  // 重新加载楼层列表
  handleBuildingChange(form.value.buildingIds);
};
const handleOut = async (row: any) => {
  dialogVisibleOut.value = true;
  formDataOut.value.contractId = row.id;
};

// 退租对话框状态和数据
const dialogVisibleOut = ref(false);
const formDataOut = ref({
  contractId: '',
  checkOutTime: '',
  cause: '',
  isOwed: false,
  remark: ''
});

const rulesOut = {
  checkOutTime: [{ required: true, message: '请选择退租日期', trigger: 'change' }],
  cause: [{ required: true, message: '请输入退租原因', trigger: 'blur' }],
  isOwed: [{ required: true, message: '请选择是否欠费', trigger: 'change' }]
};

const submitOutForm = async () => {
  try {
    // @ts-ignore
    const outForm = proxy.$refs.outForm;
    if (!outForm) {
      proxy?.$modal.msgError('表单未加载，请稍后再试');
      return;
    }
    await outForm.validate();

    // const confirmResult = await proxy?.$modal.confirm('确定要提交退租申请吗？', '确认', {
    //   confirmButtonText: '确定',
    //   cancelButtonText: '取消',
    //   type: 'warning'
    // });
    // if (confirmResult !== 'confirm') return;
    const res = await checkOutContract(formDataOut.value);
    if (res.code === 200) {
      proxy.$modal.msgSuccess('退租申请提交成功');
      dialogVisibleOut.value = false;
      getList();
    }
  } catch (error) {
    // const errorMsg = error?.response?.data?.error || error?.msg || '操作失败，请稍后重试';
    proxy.$modal.msgError('提交失败');
  }
};

const handleArrearsChangeOut = (value: boolean) => {
  if (!value) {
    formDataOut.value.arrearsAmount = 0;
  }
};
// 移除楼层
const removeFloor = (floorId: string | number) => {
  form.value.floorIds = form.value.floorIds.filter((id) => id !== floorId);
  // 重新加载房间列表
  handleFloorChange(form.value.floorIds);
};

// 添加楼宇
const addBuilding = () => {
  // 这里可以添加选择楼宇的逻辑，例如打开一个选择对话框
  // 暂时先添加一个示例楼宇
  const newBuildingId = 1; // 示例ID
  if (!form.value.buildingIds.includes(newBuildingId)) {
    form.value.buildingIds.push(newBuildingId);
    handleBuildingChange(form.value.buildingIds);
  }
};

// 添加楼层
const addFloor = () => {
  // 这里可以添加选择楼层的逻辑，例如打开一个选择对话框
  // 暂时先添加一个示例楼层
  const newFloorId = 1; // 示例ID
  if (!form.value.floorIds.includes(newFloorId)) {
    form.value.floorIds.push(newFloorId);
    handleFloorChange(form.value.floorIds);
  }
};

// 添加房间
const addRoom = () => {
  // 这里可以添加选择房间的逻辑，例如打开一个选择对话框
  // 暂时先添加一个示例房间
  const newRoomId = 1; // 示例ID
  if (!form.value.roomIds.includes(newRoomId)) {
    form.value.roomIds.push(newRoomId);
  }
};

// 移除房间
const removeRoom = (roomId: string | number) => {
  form.value.roomIds = form.value.roomIds.filter((id) => id !== roomId);
};

// 获取楼宇名称
const getBuildingName = (buildingId: string | number) => {
  const building = buildingList.value.find((b) => b.id === Number(buildingId));
  return building ? building.name : '';
};

// 获取楼层名称
const getFloorName = (floorId: string | number) => {
  const floor = floorList.value.find((f) => f.id === Number(floorId));
  return floor ? floor.name : '';
};

// 获取房间名称
const getRoomName = (roomId: string | number) => {
  const room = roomList.value.find((r) => r.id === Number(roomId));
  return room ? room.name : '';
};

/** 提交按钮 */
const submitForm = () => {
  tenantFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateContract(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addContract(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TenantVO) => {
  // const _ids = row?.id || ids.value;
  // await proxy?.$modal.confirm(`是否确认删除此数据项？`);
  // loading.value = true;
  // await removeContract(_ids).finally(() => (loading.value = false));
  const buildingIds = row?.id || ids.value;
  await proxy?.$modal.confirm(`是否确认删除选中的数据？`);
  await removeContract(buildingIds);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

/** 同步租户套餐按钮操作 */
const handleSyncTenantPackage = async (row: TenantVO) => {};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/tenant/export',
    {
      ...queryParams.value
    },
    `tenant_${new Date().getTime()}.xlsx`
  );
};

// 显示新增项目弹窗
const showAddItemDialog = () => {
  // Object.assign(newItemData, initNewItemData);
  newItemData.value = { region: '', building: '', floor: '', room: '', area: 0, remark: '', buildingDetail: '' };
  addItemDialog.visible = true;
  addItemDialog.title = '选择房源';
};

// 删除选中项目
const removeSelectedItem = (index: number) => {
  form.value.parkContractDetails.splice(index, 1);

  // 重新计算总面积，确保使用Number转换
  const totalArea = form.value.parkContractDetails.reduce((sum: number, detail: any) => {
    return sum + (Number(detail.area) || 0);
  }, 0);
  form.value.leaseArea = totalArea;
};

// 添加项目
const addItemSubmit = () => {
  if (newItemData.value.buildingDetail) {
    // 判断选择房间是否已经在form.value.parkContractDetails中
    if (form.value.parkContractDetails.some((item) => item.id === newItemData.value.buildingDetail)) {
      proxy?.$modal.msgError('选择的房间已存在');
      return;
    }
    console.log('newItemData:', newItemData.value);
    //根据newItemData.value 中region 在 districtList.value 中查找对应name
    const district = districtList.value.find((item) => item.id === newItemData.value.region);
    console.log('district:', district);
    newItemData.value.districtName = district?.districtName || '';
    console.log('buildingDetailSelList.value:', buildingDetailSelList.value);
    // 根据buildingDetail查询对应数据
    const selectedDetail = buildingDetailSelList.value.find((item) => item.id === newItemData.value.buildingDetail);
    console.log('selectedDetail:', selectedDetail);
    const para = {
      ...(selectedDetail || {}),
      // 添加查询到的楼宇详情数据
      desc: newItemData?.remark || '',
      houseId: selectedDetail?.id || '',
      districtId: newItemData.value.region || '',
      districtName: newItemData.value.districtName || '',
      area: selectedDetail?.houseArea || 0 // 确保添加面积字段
    };
    console.log('para:', para);

    form.value.parkContractDetails.push({ ...para });

    // 重新计算总面积，确保使用Number转换
    const totalArea = form.value.parkContractDetails.reduce((sum: number, detail: any) => {
      return sum + (Number(detail.area) || 0);
    }, 0);
    form.value.leaseArea = totalArea;

    console.log('form.value.:', form.value);
    addItemDialog.visible = false;
  } else {
    proxy?.$modal.msgSuccess('请选择房源');
  }
};

// 表格行样式
const tableRowClassName = ({ row }: { row: TenantVO }) => {
  if (row.expiryStatus === 'expired') {
    return 'expired-row';
  } else if (row.expiryStatus === 'expiring_soon') {
    return 'warning-row';
  }
  return '';
};
getQyList();
getList();
getDistrictList();
const buildingSelList = ref([]);
const handleAreaChange = async (regionId: number) => {
  // 清空楼宇选择
  buildingSelList.value = [];
  newItemData.value.building = '';
  newItemData.value.buildingDetail = '';
  if (!regionId) return;
  // const selParam = {
  //   pageNum: 1,
  //   pageSize: 10,
  //   districtId: regionId
  // };
  try {
    // 调用查询楼宇接口
    const res = await getBuildingList({ pageNum: 1, pageSize: 100, districtId: regionId });
    buildingSelList.value = res.rows;
  } catch (error) {
    console.error('获取楼宇列表失败:', error);
    ElMessage.error('获取楼宇列表失败，请重试');
  }
};

const buildingDetailSelList = ref([]);
const handleHouseChange = async (regionId: number) => {
  // 清空楼宇选择
  buildingDetailSelList.value = [];
  newItemData.value.buildingDetail = '';

  if (!regionId) return;
  const selParam = {
    pageNum: 1,
    pageSize: 100,
    housingId: regionId
  };
  try {
    // 调用查询楼宇接口
    const res = await listHousingDetails(selParam);
    buildingDetailSelList.value = res.rows;
  } catch (error) {
    const errorMsg = error?.response?.data?.error || error?.message || '操作失败，请稍后重试';
    ElMessage.error(errorMsg);
  }
};
const formatDate = (row: any, column: any, cellValue: string) => {
  if (!cellValue) return '';
  const date = new Date(cellValue);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
};
const formatDate2 = (cellValue: string) => {
  if (!cellValue) return '';
  const date = new Date(cellValue);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
};
// 计算总面积（所有合同详情中的面积总和）
const totalArea = computed(() => {
  if (!form.value.parkContractDetails || form.value.parkContractDetails.length === 0) {
    return 0;
  }
  return form.value.parkContractDetails.reduce((sum: number, detail: any) => {
    return sum + (Number(detail.area) || 0);
  }, 0);
});

// 监听parkContractDetails变化，自动更新总面积
watch(
  () => form.value.parkContractDetails,
  (newDetails) => {
    if (newDetails && Array.isArray(newDetails)) {
      const calculatedTotal = newDetails.reduce((sum: number, detail: any) => {
        return sum + (Number(detail.area) || 0);
      }, 0);
      form.value.totalArea = calculatedTotal;
    }
  },
  { deep: true }
);
</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

:deep(.expired-row) {
  --el-table-tr-bg-color: var(--el-color-danger-light-9);
}

:deep(.warning-row) {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.select-container {
  display: flex;
  align-items: center;
}

.selected-items {
  margin-bottom: 10px;
}

.selected-items .el-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.add-button {
  margin-top: 5px;
}
</style>
